//
//  BHSportTimerViewController.swift
//  BigHealth
//
//  Created by 蔺百好 on 2021/7/15.
//

import UIKit

class BHSportTimerViewController: BHBaseViewController {
    
    @IBOutlet weak var slog_view: UIView!
    @IBOutlet weak var sport_name_label: UILabel!
    @IBOutlet weak var fighting_label: UILabel!
    
    @IBOutlet weak var time_label: UILabel!
    
    @IBOutlet weak var kilor_label: UILabel!
    @IBOutlet weak var kilor_per_label: UILabel!
    
    @IBOutlet weak var pauseBtn: UIButton!
    @IBOutlet weak var restartBtn: UIButton!
    @IBOutlet weak var endSportBtn: UIButton!
    
    @IBOutlet weak var center_x: NSLayoutConstraint!
    /**运动类型  1跑步  2其他计时运动*/
    var sportType: Int = 1
    var sportTitle: String = ""
    
    // 计步器
    lazy var pedometerManager = BHCMPedimeter.init()
    fileprivate var kilorTotal: Double = 0.00
    fileprivate var kilorTemp: Double = 0.00
    fileprivate var startTime: String = ""
    fileprivate var endTime: String = ""
    fileprivate var time: Int = 0
    fileprivate var timer: Timer?
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.view.backgroundColor = .color_2D2F37
        self.bh_navigationBar.removeFromSuperview()
        self.canPopBack = false
        
        self.sport_name_label.text = self.sportTitle
        self.pauseBtn.addLayerCorner(50, 0, .white)
        self.restartBtn.addLayerCorner(50, 0, .white)
        self.endSportBtn.addLayerCorner(50, 0, .white)
        
        self.slog_view.addLayerCorner(4, 0.5, .color_34CE98)
        
        if self.sportType == 2 {
            self.kilor_label.isHidden = true
            self.kilor_per_label.isHidden = true
            self.center_x.constant = -50
        }else {
            
            self.pedometerManager.stepPedometerHandler = {[weak self] distance in
                self?.kilorTemp = distance/1000.0
                
                self?.configKilor()
            }
            self.pedometerManager.startPedometer()
        }

        self.startTime = Date.timeText
        
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCount), userInfo: nil, repeats: true)
        self.timer?.fire()
        
        NotificationCenter.default.addObserver(self, selector: #selector(appBecomeActive), name: NSNotification.Name.init(rawValue: String.applicationActiveNotificationKey), object: nil)

        NotificationCenter.default.addObserver(self, selector: #selector(appSleepAct), name: NSNotification.Name.init(rawValue: String.applicationSleepNotificationKey), object: nil)
        
        
    }
    
    @objc func timerCount() {
        self.time += 1
        
        let result = self.secondsToHoursMinutesSeconds(seconds: self.time)
        
        let timeStr = String.init(format: "%.2d:%.2d:%.2d", result.0,result.1,result.2)
        self.time_label.text = timeStr
    }

    func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
      return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
    }

    @IBAction func pauseSportAct(_ sender: UIButton) {
        self.pauseBtn.isHidden = true
        self.restartBtn.isHidden = false
        self.endSportBtn.isHidden = false
        
        if self.sportType == 1 {
            self.pedometerManager.stopPedometer()
            
            // 拿总距离
            self.kilorTotal = self.kilorTemp+self.kilorTotal
            
        }
        self.timer?.pause()
    }
    
    
    
    @IBAction func restartSportAct(_ sender: UIButton) {
        self.pauseBtn.isHidden = false
        self.restartBtn.isHidden = true
        self.endSportBtn.isHidden = true
        if self.timer == nil {
            self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerCount), userInfo: nil, repeats: true)
        }
        if self.sportType == 1 {
            self.kilorTemp = 0.0
            
            self.pedometerManager.startPedometer()
        }
        self.timer?.start(1)
    }
    
    @IBAction func endSportAct(_ sender: Any) {
        
        self.timer?.pause()
        self.timer?.invalidate()
        self.timer = nil
        
        self.endTime = Date.timeText
        self.createService()
    }
    
    
    private func configKilor() {
        DispatchQueue.main.async {
            self.kilor_label.text = String.init(format: "%.2f", self.kilorTotal+self.kilorTemp)
        }
    }
    
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        get {
            return .lightContent
        }
    }
}

extension BHSportTimerViewController {
    @objc func appBecomeActive() {
        let sleepTime = BHCache.load_appSleepTime()
        if sleepTime == 0 {
            return
        }
        
        let now = Date.currentTimeValue - sleepTime
        
        self.time = self.time+now
        let result = self.secondsToHoursMinutesSeconds(seconds: self.time)
        
        let timeStr = String.init(format: "%.2d:%.2d:%.2d", result.0,result.1,result.2)
        self.time_label.text = timeStr
        self.timer?.start(1)
    }
    
    @objc func appSleepAct() {
        if  self.timer != nil {
            self.timer?.pause()
        }
    }
}


// MARK: 其他运动
extension BHSportTimerViewController {
    func createService()  {
        let dic = self.appendDic()
        SVProgressHUD.show()
        let manager = BHHTTPClient.init()
        manager.post(url: String.sport_create_runOrOther_url, paramters: dic) { (success, errorMsg, responseDic) in
            SVProgressHUD.dismiss()
            if success == true {
                BHToast.toast(text: "运动已记录")
                DispatchQueue.main.asyncAfter(deadline: .now()+1.5) {
                    self.navigationController?.popViewController(animated: true)
                }
            }else {
                BHToast.toast(text: errorMsg)
            }
        }
    }
    
    
    func appendDic() -> [String:Any] {
        var dic: [String:Any] = [:]
        dic["title"] = self.sportTitle
        dic["startTime"] = self.startTime
        dic["endTime"] = self.endTime
        if self.sportType == 1 {
            dic["km"] = String.init(format: "%.2f", self.kilorTotal)
        }
        return dic
    }
}
